﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WXApi.Model;
using WxTenpay.Common;
using WxTenpay.Service.Model;
using WxTenpay.Service;

namespace WXApi.Controllers
{

    /// <summary>
    /// 登入接口
    /// </summary>
    /// 
    [Route("[controller]/[action]")]
    [ApiController]
    public class LoginApiController : ReqDataControllerBase
    {
        private readonly ISysLog syslog;
        private readonly ISysUser sysuser;
        private readonly ISysLoginLog sysloginlog;

        public LoginApiController(ISysUser _sysuse, ISysLog _syslog, ISysLoginLog _sysloginlog)
        {
            syslog = _syslog;
            sysuser = _sysuse;
            sysloginlog = _sysloginlog;
        }

        /// <summary>
        /// 登入接口 
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult Login([FromForm] UserDto user)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(user.Vcode))
                    return Error("验证码异常！");

                var code = DESEncrypt.MD5Decrypt(user.Vcode);
                if (user.Code.ToUpper() != code.ToUpper())
                    return Error("验证码错误！");


                string pwd = DESEncrypt.MD5Encrypt(user.Pwd);

                var model = sysuser.GetModel(x => x.UserName == user.UserNo && x.Password == pwd);
               
                if (model!=null)
                {
                    if (model.IsDel == 1)
                        return Error("对不起您的账号被锁定，请联系管理员！");

                    var token = DESEncrypt.MD5Encrypt(model.GuId);
                    // return Success(token);

                    SuccessLogDto loginmodel = new SuccessLogDto();
                    loginmodel.data = token;
                    loginmodel._sysloginlog = sysloginlog;
                    loginmodel.loginlogmodel = new SysLoginLogEntity { Type =0, Content = "用户登入",UserGuId= model.GuId };
                    return SuccessLog(loginmodel);

                }
                else
                    return Error("账号或密码错误！");
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "LoginApi/Login", Content = ex.ToString(), Name = "登入接口" };
                return ErrorLog(model);

            }
        }


        /// <summary>
        /// 定时任务测试地址 
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult JobsTest()
        {
            try
            {
                return Success( "接口成功");
            }
            catch (Exception ex)
            {
              
                return Error("系统异常！");

            }
        }

    }
}
